<template>
  <div>
    <div v-if="viewModel" class="report-action mb-3 mt-4">
      <el-button type="primary" :loading="printLoading" @click="printPage">
        <i class="fa fa-print"></i>
        打印
      </el-button>
    </div>
    <div :id="printId">
      <table class="table table-bordered table-vertical-middle" v-loading="initLoading">
        <tr>
          <td rowspan="6" class="text-center font-weight-bold" width="4%">审批登记</td>
          <td class="td-label" width="12%">贷款人姓名</td>
          <td colspan="3" width="36%">{{ relatedData.customer_name || '-' }}</td>
          <td class="td-label" width="12%">住所</td>
          <td colspan="3" width="36%">{{ relatedData.address || '-' }}</td>
        </tr>
        <tr>
          <td class="td-label">联系人</td>
          <td colspan="3">{{ relatedData.corp_name || relatedData.corp_name || '-' }}</td>
          <td class="td-label">联系电话</td>
          <td colspan="3">{{ relatedData.mobile_no || '-' }}</td>
        </tr>
        <tr>
          <td class="td-label">合同类型</td>
          <template v-if="viewModel">
            <td width="15%">
              {{ enumContractType[contract.contract_type] }}
            </td>
            <td colspan="2">
              {{ contract.credit_contract_no }}
            </td>
          </template>
          <template v-else>
            <td colspan="2" class="input-td">
              <el-radio-group v-model="contract.contract_type">
                <el-radio
                  v-for="(label, value) of enumContractType"
                  :key="value"
                  :label="value"
                  class="mx-2"
                >
                  {{ label }}
                </el-radio>
              </el-radio-group>
            </td>
            <td class="input-td">
              <div class="d-flex align-items-center">
                <input
                  class="form-control"
                  placeholder="合同编号"
                  v-model="contract.credit_contract_no"
                />
              </div>
            </td>
          </template>
          <td class="td-label">授信/借款金额</td>
          <td :class="viewModel ? '' : 'input-td'" colspan="3">
            <span v-if="viewModel">{{ contract.reply_funds }} 万元</span>
            <div class="d-flex align-items-center" v-else>
              <input
                type="number"
                class="form-control"
                placeholder="请填写"
                v-model="contract.reply_funds"
                @input="calcBankBillFunds"
              />
              <div class="px-3 text-muted" style="min-width: 60px">万元</div>
            </div>
          </td>
        </tr>
        <tr>
          <td class="td-label">保证合同号</td>
          <td :class="viewModel ? '' : 'input-td'" colspan="3">
            <span v-if="viewModel">{{ contract.ensure_contract_no }}</span>
            <div class="d-flex align-items-center" v-else>
              <input
                class="form-control"
                placeholder="请填写"
                v-model="contract.ensure_contract_no"
              />
            </div>
          </td>
          <td class="td-label">签约时间</td>
          <td :class="viewModel ? '' : 'input-td'" colspan="3">
            <span v-if="viewModel">
              {{ $utils.dateFormat(contract.contract_date, 'yyyy-MM-dd') }}
            </span>
            <el-date-picker
              v-else
              v-model="contract.contract_date"
              class="w-100"
              placeholder="授信合同签约时间"
              type="date"
              value-format="yyyy-MM-dd"
              :clearable="true"
            ></el-date-picker>
          </td>
        </tr>
        <tr>
          <td class="td-label">授信期限</td>
          <td :class="viewModel ? '' : 'input-td'" colspan="3">
            <span v-if="viewModel">{{ contract.load_years }} 年</span>
            <div class="d-flex align-items-center" v-else>
              <input
                type="number"
                class="form-control"
                placeholder="授信期限"
                v-model="contract.load_years"
              />
              <div class="px-3 text-muted" style="min-width: 60px">年</div>
            </div>
          </td>
          <td class="td-label">备注</td>
          <td :class="viewModel ? '' : 'input-td'" colspan="3">
            <span v-if="viewModel">{{ contract.remark }}</span>
            <div class="d-flex align-items-center" v-else>
              <input class="form-control" placeholder="请填写" v-model="contract.remark" />
            </div>
          </td>
        </tr>
      </table>
    </div>
    <div class="text-center py-4" v-if="!viewModel">
      <el-button type="primary" class="btn-long" :loading="loading" @click="submit">
        {{ hasContract ? '修改' : '提交' }}登记
      </el-button>
      <el-button class="btn-long" :loading="loading" @click="handleReject" type="danger">
        拒绝
      </el-button>
    </div>
  </div>
</template>
<script>
import { printA4 } from '@vimi/utils-tool'
import { enumContractType } from '@/credit/plugins/enumTown'
export default {
  components: {},
  props: {
    relatedData: {
      type: Object,
      default: () => ({}),
    },
    viewModel: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      enumContractType,
      initLoading: false,
      loading: false,
      printLoading: false,
      contract: { contract_type: '1' },
    }
  },
  computed: {
    org() {
      return this.$store.getters.org
    },
    user() {
      return this.$store.getters.user
    },
    hasContract() {
      return !!this.contract.entrust_contract_id
    },
    relatedId() {
      return this.relatedData.customer_related_id
    },
    printId() {
      return `register-contract-${this.relatedId}`
    },
    replyFunds() {
      return (
        +(
          this.relatedData.res_funds ||
          this.relatedData.reply_funds ||
          this.relatedData.bank_approved_funds
        ) || 0
      )
    },
  },
  watch: {
    relatedData: {
      handler: function () {
        this.getData()
      },
      deep: true,
      immediate: true,
    },
  },
  created() {},
  mounted() {},
  methods: {
    async getData() {
      if (!this.relatedId) return

      this.initLoading = true
      const [res] = await this.$utils.promise(
        this.$api.getData(this.$serviceName, 'entrust_contract', {
          'customer_related_id.eq': this.relatedId,
        })
      )
      this.initLoading = false
      this.contract = (res && res.data && res.data[0]) || { contract_type: '1' }
      if (!this.contract.reply_funds) {
        this.$set(this.contract, 'reply_funds', this.relatedData.bank_approved_funds)
      }
    },
    submit() {
      if (!this.validator()) return

      const promise = this.hasContract ? this.putData() : this.postData()
      this.loading = true
      promise
        // .then(() => this.updateRelatedStatus())
        .then(() => {
          this.$message.success('登记成功')
          this.$emit('success', this.hasContract ? 0 : 1)
        })
        .catch(err => {
          this.$message.error('登记失败')
          throw err
        })
        .finally(() => {
          this.loading = false
        })
    },
    handleReject() {
      const data = {
        bank_approved_check_person: this.user.userId,
        bank_approved_time: this.$utils.dateFormat(new Date(), 'yyyy-MM-dd hh:mm:ss'),
        bank_approval_status: '2',
      }
      this.$prompt('请输入拒绝说明', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputValidator: value => (!value ? '请输入拒绝说明' : true),
      }).then(({ value }) => {
        data.bank_approval_des = value
        this.$api
          .updateData(this.$serviceName, 'customer_related', this.relatedId, data)
          .then(res => {
            this.$message.success('已拒绝！')
            this.$emit('success', res)
          })
          .catch(() => this.$message.error(`提交失败，请重试！`))
      })
    },
    putData() {
      return this.$api.updateData(
        this.$serviceName,
        'entrust_contract',
        this.contract.entrust_contract_id,
        this.contract
      )
    },
    postData() {
      this.contract.customer_related_id = this.relatedId
      this.contract.bank_name = this.relatedData.bank_name || this.org.orgName
      return this.$api.addData(this.$serviceName, 'entrust_contract', this.contract)
    },
    updateRelatedStatus() {
      return this.$api.updateData({
        table: 'customer_related',
        id: this.relatedId,
        data: {
          contract_approval_status: 1,
        },
      })
    },
    validator() {
      const enumValid = {
        // load_date: '请选择放款时间',
        credit_contract_no: '请填写授信合同/借款编号',
        ensure_contract_no: '请填写保证合同号',
        // contract_date: '请选择授信合同/借款合同签约时间',
        // load_end_date: '请选择还款结束时间'
      }

      const keys = Object.keys(enumValid)
      for (const key of keys) {
        if (!this.contract[key]) {
          this.$message.error(enumValid[key])
          return false
        }
      }

      return true
    },
    calcBankBillFunds() {
      const funds = Number.parseFloat(this.contract.reply_funds) || 0
      // if (funds > this.replyFunds) {
      //   this.contract.reply_funds = this.replyFunds
      //   this.$message.error(`不能大于金额${this.replyFunds}万元`)
      // } else
      if (funds < 0) {
        this.contract.reply_funds = ''
        this.$message.error(`不能小于0`)
      }
    },
    printPage() {
      printA4(
        document.getElementById(this.printId).innerHTML,
        `
        body {font-family: SimSun;}
        .table-vertical-middle td {vertical-align: middle;}
        .td-label {background-color: #f8f9fa;text-align: center;}
      `
      )
    },
  },
}
</script>
<style lang="scss" scoped>
.table-vertical-middle td {
  vertical-align: middle;
}
.td-label {
  background-color: #f8f9fa;
  text-align: center;
}
.input-td {
  background-color: #ffffee;
}
</style>
